package com.dengbw.systemtransfer.component;

import com.dengbw.systemtransfer.annotations.TimeSpeaker;
import com.dengbw.systemtransfer.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dengbw
 * @date 2021/11/11 4:07 下午
 */
@Slf4j
@Aspect
@Component
public class TimeSpeakerAsp {

    private Map<String, LocalDateTime> starts;

    @Pointcut("@annotation(timeSpeaker)")
    private void pointCut(TimeSpeaker timeSpeaker) {
    }

    @Before(value = "pointCut(timeSpeaker)", argNames = "timeSpeaker")
    public void before(TimeSpeaker timeSpeaker) {
        String name = timeSpeaker.value();
        if (starts == null) {
            starts = new HashMap<>();
        }
        starts.put(name, LocalDateTime.now());
        log.info(name + " started");
    }

    @AfterReturning(value = "pointCut(timeSpeaker)", argNames = "timeSpeaker")
    public void after(TimeSpeaker timeSpeaker) {
        if (!starts.containsKey(timeSpeaker.value())) {
            log.info(timeSpeaker.value() + " finished");
            return;
        }
        log.info(timeSpeaker.value() + " finished, used " + TimeUtils.duration(starts.get(timeSpeaker.value())));
    }
}
